// pages/order/orderDetail/orderDetail.js
const app = getApp();

let api = require('../../../utils/api.js');

var QQMapWX = require('../../../public/js/qqmap-wx-jssdk.min.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dialogShow:false,
    money:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    let that = this
    // console.log("options+++++++++++", options);
    if (options.id) {

      var orderId = options.id;
      that.setData({
        orderId: orderId
      });
    }
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          orderId: orderId,
          winWidth: res.windowWidth,
          winHeight: res.windowHeight - app.globalData.navHeight
        });
      }
    });


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    var orderId = that.data.orderId;
    var token = wx.getStorageSync('TOKEN');
    var param = {
      id: orderId,
    };
    var stateData = [];
    stateData[0] = '待接货';
    stateData[1] = '待装货';
    stateData[2] = '待收货';
    stateData[3] = '待发货';
    stateData[4] = '待送达';
    stateData[5] = '已达到';
    stateData[6] = '待评价';
    api._get('/omc/order/detail/' + orderId, param, token).then(res => {
      // console.log(res);
      var detaildata = res.result;
      var shipmentTime = [];
      detaildata['showShipmentTime'] = {};
      shipmentTime['start'] = detaildata.shipmentTime.start * 1000;
      shipmentTime['end'] = detaildata.shipmentTime.end * 1000;
      detaildata['showShipmentTime'] = {
        start: app.formatDate(shipmentTime['start'], 'YYYY-MM-DD H'),
        end: app.formatDate(shipmentTime['end'], 'H')
      }


      var arrivalTime = [];
      detaildata['showArrivalTime'] = [];
      arrivalTime['start'] = detaildata.arrivalTime.start * 1000;
      arrivalTime['end'] = detaildata.arrivalTime.end * 1000;
      detaildata['showArrivalTime'] = {
        start: app.formatDate(arrivalTime['start'], 'YYYY-MM-DD H'),
        end: app.formatDate(arrivalTime['end'], 'H')
      }

      
      if (detaildata.freightWeight.max && detaildata.freightWeight.min) {
        detaildata["showfreightWeight"] = detaildata.freightWeight.min + '-' + detaildata.freightWeight.max + '吨';
      } else if (detaildata.freightWeight.max && !detaildata.freightWeight.min) {
        detaildata["showfreightWeight"] = detaildata.freightWeight.max + '吨';
      } else if (!detaildata.freightWeight.max && detaildata.freightWeight.min) {
        detaildata["showfreightWeight"] = detaildata.freightWeight.min + '吨';
      }

      if (detaildata.freightBulk.max && detaildata.freightBulk.min) {
        detaildata["showfreightBulk"] = detaildata.freightBulk.min + '-' + detaildata.freightBulk.max + '方';
      } else if (detaildata.freightWeight.max && !detaildata.freightBulk.min) {
        detaildata["showfreightBulk"] = detaildata.freightBulk.max + '方';
      } else if (!detaildata.freightBulk.max && detaildata.freightBulk.min) {
        detaildata["showfreightBulk"] = detaildata.freightBulk.min + '方';
      }

      if (detaildata.remarks) {
        detaildata['showRemarks'] = detaildata.remarks;
      } else {
        detaildata['showRemarks'] = '无';
      }
      detaildata['showSpecialAsk'] = '';
      if (detaildata.specialAsk.length != 0) {
        detaildata.specialAsk.forEach((v, i) => {
          if (i == 0) {
            detaildata['showSpecialAsk'] += v;
          } else {
            detaildata['showSpecialAsk'] += ',' + v;
          }
        })
      }
      if (detaildata.state < 0) {
        detaildata['showState'] = '取消中';
      } else {
        if (detaildata.state == 6) {
          if (detaildata.isEvaluate == 0) {
            detaildata['showState'] = '待评价';
          } else {
            detaildata['showState'] = '已评价';
          }
        } else {
          detaildata['showState'] = stateData[detaildata['state']];
        }
      }

      var createTime = detaildata['createTime'] * 1000;
      detaildata['showCreateTime'] = app.formatDate(createTime, 'YYYY-MM-DD');
      that.setData({
        detailData: detaildata
      });
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // },
  // 打电话
  callExpert: function(e) {
    // console.log(e.currentTarget.dataset.phone)
    var phone = e.currentTarget.dataset.phone;
    app.callExpert();
  },
  /**
   * 订单操作
   */
  orderAction: function(e) {
    // console.log(e.currentTarget.dataset.orderid);
    var token = wx.getStorageSync('TOKEN');
    var data = {
      id: e.currentTarget.dataset.orderid,
      state: parseInt(e.currentTarget.dataset.state),
      token: token
    };
    var state = parseInt(e.currentTarget.dataset.state);
    var countent='';
    if (state == 12) {
      countent = '确认收货前，请确认已收到货物，并检查货物是否完好。点击确定后，默认订单已完成。'
    } else if (state == 2) {
      countent = '确认申请取消订单。点击确定后，申请将推送到司机端，待司机确认。'
    } else if (state == 1) {
      countent = '确认取消订单。点击确定后，订单将被取消。'
    } else if (state == 7) {
      countent = '确认拒绝司机的取消订单请求'
    } else if (state == 6) {
      countent = '确认同意司机的取消订单请求'
    }

    wx.showModal({
      content: countent,
      success: function(res) {
        if (res.confirm) {
          // console.log('用户点击确定')

          var token = wx.getStorageSync('TOKEN');
          var data = {
            id: e.currentTarget.dataset.orderid,
            state: parseInt(e.currentTarget.dataset.state),
            token: token
          }
          app.orderAction(data).then(function(code) {
            // console.log(code);
            if (code == 200) {
              wx.switchTab({
                url: '/pages/order/order',
                success: function(e) {
                  var page = getCurrentPages().pop();
                  if (page == undefined || page == null) return;
                  page.onLoad();
                }
              })
            } else if (res.cancel) {
              // console.log('用户点击取消')
            }
          })
        }

      }
    })


  },
  showMap: function(e){
    // console.log(e.currentTarget.dataset.address)
    var qqmapsdk = new QQMapWX({
      key: 'NT2BZ-Y5Q34-YYCUF-DLQNZ-KW3L5-TCFCC' // 必填
    });
    var _this = this;
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: e.currentTarget.dataset.address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function(res) {//成功后的回调
        // console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        wx.getLocation({
          type: 'wgs84', 
          success: function (res) {
            wx.openLocation({//​使用微信内置地图查看位置。
              latitude: latitude,//要去的纬度-地址
              longitude: longitude,//要去的经度-地址
              name: e.currentTarget.dataset.address,
              address: e.currentTarget.dataset.address
            })
          }
        })
      }
    })

   
  },
  editMoney:function(){
    // api._get('/omc/order/detail/' + orderId, param, token).then(res => {
    // })
    this.setData({
      dialogShow: true,
    })
  },
  
  // 关闭弹框
  _cancelEvent: function(e) {
    this.setData({
      money:null,
      dialogShow: false,
    });
  },
  
  // 输入监听
  inputWacth: function(e) {
    // console.log(e);
    var that=this;
    let value = e.detail.value;

    that.setData({
      money: value
    });
  },
  // 提交用户名
  _nameConfirmEvent: function(e) {
    var that = this;
    var token = wx.getStorageSync('TOKEN');
    var value = that.data.money;
    if (value == "") {
      that.toast("金额不可为空");
      return;
    }
console.log(e)
    var params = {
      orderId: that.data.orderId,
      price: value
    }
    api._get('/omc/order/discuss', params, token).then(res => {
      // driverList[item]['state'] = 0;
      console.log(res);
      if (res.code == 200) {
        that.hideModal();
        that.onShow()

      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
        })
      }
    }).catch(e => {
      // console.log(e)
    })
    // that.changeUserInfo(type, value, token, params);
  },
  
  //隐藏对话框
  hideModal: function() {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        dialogShow: false
      })
    }.bind(this), 200)
  },
})